package com.ibpd.shopping.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.assist.FloatEditor;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.ListSortUtil;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.web.controller.ext.FormModel;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.assist.ExtProductAttrEntity;
import com.ibpd.shopping.assist.ExtProductSpecEntity;
import com.ibpd.shopping.entity.CatalogEntity;
import com.ibpd.shopping.entity.ProductAttrDefineEntity;
import com.ibpd.shopping.entity.ProductAttrValueEntity;
import com.ibpd.shopping.entity.ProductEntity;
import com.ibpd.shopping.entity.SpecEntity;
import com.ibpd.shopping.service.catalog.CatalogServiceImpl;
import com.ibpd.shopping.service.catalog.ICatalogService;
import com.ibpd.shopping.service.product.IProductAttrDefineService;
import com.ibpd.shopping.service.product.IProductAttrValueService;
import com.ibpd.shopping.service.product.IProductService;
import com.ibpd.shopping.service.product.ProductAttrDefineServiceImpl;
import com.ibpd.shopping.service.product.ProductAttrValueServiceImpl;
import com.ibpd.shopping.service.product.ProductServiceImpl;
import com.ibpd.shopping.service.spec.ISpecService;
import com.ibpd.shopping.service.spec.SpecServiceImpl;
import com.sun.beans.editors.BooleanEditor;

@Controller
public class Product extends BaseController {
	@RequestMapping("Manage/Product/index.do")
	public String index(Long catalogId,Model model,HttpServletRequest req) throws IOException{
		model.addAttribute("pageTitle","商品管理");
		model.addAttribute("cataId",catalogId);
		return "manage/s_product/index";
	}
	@RequestMapping("Manage/Product/list.do")
	public void list(HttpServletResponse resp,String id,String order,Integer page,Integer rows,String sort,String queryString,HttpServletRequest req) throws IOException{
		IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
		Long tenantId=SysUtil.getCurrentTenantId(req.getSession());
		tenantId=(tenantId==null)?-1L:tenantId;
		String query="catalogId="+id;
		if(SysUtil.getCurrentLoginedUserType(req.getSession()).equals("tenant")){
			query=query+" and tenantId="+tenantId;
		}
//		productServ.getDao().clearCache();
		super.getList(req, productServ, resp, order, page, rows, sort, query);
	}
	@RequestMapping("Manage/Product/props.do")
	public String props(Long id,Model model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null || id<0L){
			model.addAttribute("errorMsg","参数错误");
			return super.ERROR_PAGE;
		}
		IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity ce=productServ.getEntityById(id);
		if(ce==null){
			model.addAttribute("errorMsg","没有该类别");
			return super.ERROR_PAGE;
		}
		model.addAttribute("pageTitle","参数设置");
		model.addAttribute("htmls",super.getHtmlString(ce, "product.prop.field"));
		model.addAttribute("entity",ce);
		return "manage/s_product/props";
	}	
	@RequestMapping("Manage/Product/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
			IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
			ProductEntity cata=productServ.getEntityById(id);
				if(cata!=null){
					//先确定参数类型
					Method tmpMethod=cata.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=cata.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(cata, val);
					productServ.saveEntity(cata);
//					productServ.getDao().clearCache();
					super.printMsg(resp, "99", cata.getId().toString(), "保存成功");		
				}else{
					super.printMsg(resp, "-1", "", "没有该商品");
				}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");			
		}
	}
	@RequestMapping("Manage/Product/toAdd.do")
	public String toAdd(Long catalogId,Model model,HttpServletResponse resp,HttpServletRequest req) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		List<ProductAttrDefineEntity> attrList=getAttrListByCataId(catalogId,ProductAttrDefineServiceImpl.Product_Attr_Define_Attrib);
		List<ProductAttrDefineEntity> paramList=getAttrListByCataId(catalogId,ProductAttrDefineServiceImpl.Product_Attr_Define_Params);
		if(attrList!=null){
			if(paramList!=null){
				for(ProductAttrDefineEntity p:paramList){
					attrList.add(p);
				}
			}
		}
		model.addAttribute("attrList",attrList);
		model.addAttribute("tenantId",SysUtil.getCurrentTenantId(req.getSession()));
		model.addAttribute("cataId",catalogId);
		model.addAttribute("type","add");
		model.addAttribute("pageTitle","添加");
		model.addAttribute("htmls",super.getHtmlString(null, "product.add.field"));
		return "manage/s_product/add";
	}
	private List<ProductAttrDefineEntity> getAttrListByCataId(Long cataId,Integer type){
		IProductAttrDefineService attrServ=(IProductAttrDefineService) getService(ProductAttrDefineServiceImpl.class);
		List<ProductAttrDefineEntity> attrList=null;
		if(type==ProductAttrDefineServiceImpl.Product_Attr_Define_Attrib)
			attrList=attrServ.getAttributeListByCatalogId(cataId);
		else
			attrList=attrServ.getParamListByCatalogId(cataId);
		if(attrList!=null && attrList.size()>0){
			return attrList;
		}else{
			ICatalogService cataServ=(ICatalogService) getService(CatalogServiceImpl.class);
			CatalogEntity ce=cataServ.getEntityById(cataId);
			if(ce==null){
				return null;
			}
			if(ce.getPid()>0){
				return getAttrListByCataId(ce.getPid(),type);
			}else{
				return null;
			}
		}
	}
	@RequestMapping("Manage/Product/toEdit.do")
	public String toEdit(Long id,Model model,HttpServletResponse resp,HttpServletRequest req) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null){
			return this.ERROR_PAGE;
		}
		IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity cata=productServ.getEntityById(id);
		if(cata==null){
			model.addAttribute("errorMsg","没有该商品");
			return this.ERROR_PAGE;
		}
		IProductAttrValueService attrServ=(IProductAttrValueService) getService(ProductAttrValueServiceImpl.class);
		List<ProductAttrValueEntity> lst=attrServ.getListByProductId(id);
		List<ExtProductAttrEntity> attrList=convert(lst);
		ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
		List<SpecEntity> specList=specServ.getProductSpecList(id);
		model.addAttribute("attrList",attrList);
		model.addAttribute("specList",specList);
		model.addAttribute("tenantId",SysUtil.getCurrentTenantId(req.getSession()));
		model.addAttribute("type","edit");
		model.addAttribute("pageTitle","编辑");
		model.addAttribute("htmls",super.getHtmlString(cata, "product.edit.field"));
		model.addAttribute("entity",cata);
		return "manage/s_product/add";
	}
	private List<ExtProductAttrEntity> convert(List<ProductAttrValueEntity> lst){
		if(lst==null || lst.size()==0)
			return null;
		List<ExtProductAttrEntity> rtnList=new ArrayList<ExtProductAttrEntity>();
		IProductAttrDefineService attrServ=(IProductAttrDefineService) getService(ProductAttrDefineServiceImpl.class);
		for(ProductAttrValueEntity av:lst){
			ProductAttrDefineEntity def=attrServ.getEntityById(av.getAttrId());
			ExtProductAttrEntity ext=new ExtProductAttrEntity();
			ext.setAttrId(av.getAttrId());
			ext.setAttrName(def.getAttrName());
			ext.setAttrValue(av.getValue());
			ext.setId(av.getId());
			ext.setOrder(def.getOrder());
			ext.setProductId(av.getProductId());
			rtnList.add(ext);
		}
		ListSortUtil a=new ListSortUtil();
		a.sort(rtnList, "order", "asc");
		return rtnList;

	}
	@RequestMapping("Manage/Product/doEdit.do")
	public void doEdit(@FormModel("product")ProductEntity product,ExtProductAttrEntity attr,ExtProductSpecEntity spec,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		ProductEntity entity =product;
		if(entity!=null && entity.getId()!=null && entity.getId()!=-1L){
			
			IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
			ProductEntity cata=productServ.getEntityById(entity.getId());
			if(cata==null){
				super.printMsg(resp, "-1", "", "没有该商品");
				return;
			}else{
				swap(entity,cata);
				productServ.saveEntity(cata);
				List<ProductAttrValueEntity> attrList=attr.getAttrList();
				if(attrList!=null){
					IProductAttrValueService attrServ=(IProductAttrValueService) getService(ProductAttrValueServiceImpl.class);
					for(ProductAttrValueEntity a:attrList){
						ProductAttrValueEntity da=attrServ.getEntityById(a.getId());
						if(da!=null){
							super.swap(a, da);
							attrServ.saveEntity(da);							
						}
					}
				}
				List<SpecEntity> specList=spec.getSpecList();
				if(specList!=null){
					ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
					for(SpecEntity s:specList){
						if(s.getId()!=null && s.getId()>0){
							SpecEntity se=specServ.getEntityById(s.getId());
							if(se!=null){
								super.swap(s, se);
								specServ.saveEntity(se);
							}
						}else{
							s.setProductId(entity.getId());
							specServ.saveEntity(s);
						}
					}
				}
				super.printMsg(resp, "99", cata.getId().toString(), "保存成功");
				return;
			}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");
			return;
		}
		
	}
	@RequestMapping("Manage/Product/doAdd.do")
	public void doAdd(@FormModel("product")ProductEntity product,ExtProductAttrEntity attr,ExtProductSpecEntity spec,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		ProductEntity entity=product;
		if(entity.getName().trim().equals("")){
			super.printMsg(resp, "-1", "-1", "参数错误");
			return;
		}
		IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
		entity.setTenantId(SysUtil.getCurrentTenantId(req.getSession()));
		productServ.saveEntity(entity);	
		IProductAttrValueService attrServ=(IProductAttrValueService) getService(ProductAttrValueServiceImpl.class);
		List<ProductAttrValueEntity> attrList=attr.getAttrList();
		for(ProductAttrValueEntity ar:attrList){
			ar.setProductId(entity.getId());
			attrServ.saveEntity(ar);
		}
		if(spec!=null){
			if(spec.getSpecList()!=null){
				ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
				for(SpecEntity sp:spec.getSpecList()){
					sp.setProductId(entity.getId());
					specServ.saveEntity(sp);
				}
			}
		}
		
		super.printMsg(resp, "99", entity.getId().toString(), "保存成功");
		 
	}
	@RequestMapping("Manage/Product/saveText.do")
	public void saveText(Long id,String content,HttpServletResponse resp) throws IOException{
		if(id==null){
			super.printMsg(resp, "-1", "", "参数错误");	
			return;
		}
		IProductService cataServ=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity pe=cataServ.getEntityById(id);
		if(pe==null){
			super.printMsg(resp, "-1", "", "没有该商品");	
		}else{
			pe.setProductHTML(content);
			cataServ.saveEntity(pe);
			super.printMsg(resp, "99", "", "操作成功");	
		}
	}
	@RequestMapping("Manage/Product/doDel.do")
	public void doDel(String ids,HttpServletResponse resp) throws IOException{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		IProductService cataServ=(IProductService) getService(ProductServiceImpl.class);
		cataServ.batchDel(ids);
		super.printMsg(resp, "99", "", "操作成功");	
	}
	@RequestMapping("Manage/Product/status.do")
	public void status(String ids,String status,HttpServletResponse resp) throws IOException{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		IProductService cataServ=(IProductService) getService(ProductServiceImpl.class);
		String[] is=ids.split(",");
		String  whereString="from "+cataServ.getTableName()+" where ";
		for(String id:is){
			whereString+="id="+id+" or ";
		}
		whereString=whereString.substring(0,whereString.length()-4);
//		cataServ.getDao().clearCache();
		List<ProductEntity> ceList=cataServ.getList(whereString, null);
		for(ProductEntity t:ceList){
			t.setStatus((status.trim().toLowerCase().equals("pass"))?ProductEntity.Status_Pass:ProductEntity.Status_UnPass);
			cataServ.saveEntity(t);
		}
		super.printMsg(resp, "99", "", "操作成功");	
	}
	@InitBinder  
	@Override
	protected void initBinder(WebDataBinder binder) {
		
		super.initBinder(binder);
		binder.registerCustomEditor(Float.class, "price,nowPrice", new FloatEditor());
	    binder.registerCustomEditor(Boolean.class, "isnew,sale,isTimePromotion,",new BooleanEditor());
	}
}